package com.wrupple.muba.common.client.application;

import java.util.ArrayList;
import java.util.Collection;

import com.google.gwt.core.client.GWT;
import com.google.gwt.core.client.Scheduler;
import com.wrupple.muba.common.shared.StateTransition;


public abstract class DataCallback<T> implements StateTransition<T> {
	protected T result;
	private ArrayList<StateTransition<T>> hooks;
	
	@Override
	public void setResult(T result) {
		this.result = result;
		if(hooks!=null){
			for(StateTransition<T>callback : hooks){
				callback.setResult(result);
				Scheduler.get().scheduleDeferred(callback);
			}
		}
	}
	
	@Override
	public void hook(StateTransition<T> callback){
		if(this==callback){
			//the programer is just beeing an asshole
			return;
		}
		if(hooks==null){
			hooks = new ArrayList<StateTransition<T>>();
		}
		hooks.add(callback);
	}


	@Override
	public Collection<StateTransition<T>> getChildren() {
		return hooks;
	}

	@Override
	public void setResultAndFinish(T result) {
		setResult(result);
		if(GWT.isClient()){
			Scheduler.get().scheduleDeferred(this);
		}else{
			execute();
		}
	}
	
	public static <T> DataCallback<T> nullCallback(){
		return new DataCallback<T>(){

			@Override
			public void execute() {
				
			}
			
		};
	}

}
